package com.ujs.code.binarysearch;

/**
 * @author zhangshihao
 * @create 2023-09-10 21:58
 */
public class BinarySearch {
    public static void main(String[] args) {
        int[] nums = {-1, 2, 4, 6, 7, 9};
        int target = 2;
        BinarySearch binarySearch = new BinarySearch();
        int search = binarySearch.search(nums, target);
        System.out.println(search);
    }

    /**
     * 二分查找的算法实现
     * @param nums 升序排列的列表，且列表中的每个元素只出现一次
     * @param target 目标值
     * @return 目标存在返回索引，不存在返回-1
     */
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int middle = left + (right - left) / 2;
            if (nums[middle] > target) {
                right = middle - 1;
            } else if (nums[middle] < target) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return -1;
    }
}
